package com.congee02.exit;

/**
 * @author congee02
 * @date 1/31/2023 8:50 PM
 */
public class ThreadSignExitTest {
    
    public static void main(String[] args) {
        ControllableSignPrintThread runnable = new ControllableSignPrintThread();
        runnable.start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        runnable.stopRunning();
    }
    
    
    private static class ControllableSignPrintThread extends Thread {
        
        /* 通过标志变量通知线程终止 */
        private boolean running = true;
        
        public void stopRunning() {
            running = false;
        }

        /**
         * 当其他线程调用此线程对象的 {@link #stopRunning()} 时，
         * while 条件为 false，跳出循环，当前线程结束
         */
        @Override
        public void run() {
            int i = 0;
            while (running) {
                i ++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("正在运行 " + i);
            }
            System.out.println("运行结束");
        }
    } 
    
}
